const fs = require('fs');
const promisify = require('util').promisify;
const path = require('path');
const stat = promisify(fs.stat);
const readdir = promisify(fs.readdir);
const config = require('../config/defaultConfig.js');
const isCache = require('../config/cache.js')
const ejs = require('ejs');

const mimeTypes = {
    'js': 'application/x-javascript',
    'html': 'text/html',
    'css': 'text/css',
    'txt': "text/plain" ,
    "jpg": "image/jpeg"
}
const mime = (filePath) => {

    console.log(path.extname(filePath))

    let ext = path.extname(filePath)
        .split('.').pop().split('?')[0].toLowerCase()

    if (!ext) {
        ext = filePath
    }
    return mimeTypes[ext] || mimeTypes['txt']
}

module.exports = async function (req, res, filePath) {
    filePath = filePath.split('?')[0]
    console.log('enter')
    console.log('filePath')
    try {
        const stats = await stat(filePath);
        console.log("filePath")
        if (stats.isFile()) {
            const mimeType = mime(filePath)
            console.log(mimeType, filePath);
            if (isCache(stats, req, res)) {
                console.log("isCache");
                res.statusCode = 304;
                res.end();
                return;
            }
            res.statusCode = 200;
            res.setHeader('Content-Type', mimeType);
            fs.createReadStream(filePath).pipe(res);
        } else if (stats.isDirectory()) {
            const files = await readdir(filePath);
            res.statusCode = 200;
            res.setHeader('Content-Type', 'text/html;charset=UTF-8');
            res.write(`<html><body style="background-image:url(http://${config.hostname}:${config.port}//helper/background.jpg);background-repeat: space;background-size: cover;"><div style="display:flex;">`)
            var html = '';
            for (let i = 0; i < files.length; i++) { //
                html += `<a style="display:block;margin:10px" href="http://${config.hostname}:${config.port}` +
                    req.url + '/' + files[i] + '">' + files[i] + '</a>';
            }
            res.write(html);
            res.end('</div></body></html>')
        }
    } catch (err) {
        console.log(err)
        res.statusCode = 404;
        res.setHeader('Content-Type', 'text/javascript;charset=UTF-8');
        res.end(`${filePath} is not a directory or file.`)
        return;
    }
}